﻿using RemoteSensingImageDirectServer.Models.Request.Listener;
using RemoteSensingImageDirectServer.Models.Request.Params.OGC.RasterMap;
using RemoteSensingImageDirectServer.Models.Request.Response;
using RemoteSensingImageDirectServer.Service.Common;
using RemoteSensingImageDirectServer.Service.LRU;
using RemoteSensingImageDirectServer.Untils.Extensions;
using RemoteSensingImageDirectServer.Untils.LRU;
using RemoteSensingImageDirectServer.Untils.Pool;
using RemoteSensingImageDirectServer.Untils.ScopeSpace;
using RemoteSensingImageDirectServer.Untils.Source;

namespace RemoteSensingImageDirectServer.Service.OGC.RasterMap
{
    public class SingleRasterMap : ISingleRasterMap
    {

        /// <summary>
        /// 栅格数据源瓦片服务
        /// </summary>
        private readonly IRasterSourceTile _rasterSourceTile;


        public SingleRasterMap(IRasterSourceTile rasterSourceTile)
        {
            this._rasterSourceTile = rasterSourceTile;
        }

        public ServiceResult GetTile(IRSIMapSource source, SingleWMTSParams tileParam)
        {
            var epsgCode = OsrTransformPool.Instance().GetEPSGFromSrs(tileParam.TileMatrixset);
            var tileEnv = RasterEnvelopeFactory.CreateREnvelopeFromXYZ(
                tileParam.TileCol, tileParam.TileRow, tileParam.TileMatrix, 256, epsgCode);

            var serviceResult = _rasterSourceTile.GetRasterTile(source, tileParam, tileEnv, 256, 256);

            return serviceResult;
        }

        public ServiceResult GetTile(IRSIMapSource source, SingleWMSParams tileParam)
        {
            var coordinateSystem = tileParam.Crs ?? tileParam.Srs;
            var epsgCode = OsrTransformPool.Instance().GetEPSGFromSrs(coordinateSystem);

            RasterEnvelope tileEnv = null;
            if ((tileParam.Version.Equals("1.3.0") || tileParam.Version.Equals("1.0.0")) && epsgCode != 3857)
            {
                //下左上右
                tileEnv = new RasterEnvelope(tileParam.BBox[1], tileParam.BBox[0], tileParam.BBox[3], tileParam.BBox[2],
                    (tileParam.BBox[3] - tileParam.BBox[1]) / tileParam.Width,
                    (tileParam.BBox[0] - tileParam.BBox[2]) / tileParam.Height);
            }
            else
            {
                tileEnv = new RasterEnvelope(tileParam.BBox[0], tileParam.BBox[1], tileParam.BBox[2], tileParam.BBox[3],
                    (tileParam.BBox[2] - tileParam.BBox[0]) / tileParam.Width,
                   (tileParam.BBox[1] - tileParam.BBox[3]) / tileParam.Height);
            }

            var serviceResult = _rasterSourceTile.GetRasterTile(source, tileParam, tileEnv, tileParam.Width, tileParam.Height);

            return serviceResult;
        }

    }
}
